// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/api';

// 获取token
const getToken = () => {
  return localStorage.getItem('admin_token');
};

// 通用请求函数
async function request(url, options = {}) {
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers,
  };

  // 如果是需要认证的请求，添加token
  const token = getToken();
  if (token && (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE')) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || '请求失败');
  }

  return await response.json();
}

// 获取模型的所有状态
export const getModelStates = async (modelId) => {
  return await request(`/models/${modelId}/states`);
};

// 创建新状态
export const createState = async (modelId, stateData) => {
  return await request(`/models/${modelId}/states`, {
    method: 'POST',
    body: JSON.stringify(stateData),
  });
};

// 更新状态
export const updateState = async (stateId, stateData) => {
  return await request(`/states/${stateId}`, {
    method: 'PUT',
    body: JSON.stringify(stateData),
  });
};

// 删除状态
export const deleteState = async (stateId) => {
  return await request(`/states/${stateId}`, {
    method: 'DELETE',
  });
};

// 批量更新状态顺序
export const reorderStates = async (modelId, states) => {
  return await request(`/models/${modelId}/states/reorder`, {
    method: 'POST',
    body: JSON.stringify({ states }),
  });
};

export default {
  getModelStates,
  createState,
  updateState,
  deleteState,
  reorderStates
};

